package goodslogic

import (
	"context"
	"mall-backend/domain/repository/dao"
	"mall-backend/domain/repository/impl"

	"mall-backend/rpc/goods/internal/svc"
	"mall-backend/rpc/goods/pb"

	"encoding/json"
	"github.com/zeromicro/go-zero/core/logx"
)

type ListCategoryLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	repo   dao.IUsersRepo
	logx.Logger
}

func NewListCategoryLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListCategoryLogic {
	return &ListCategoryLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		repo:   impl.InitUsersRepo(svcCtx.DB),
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListCategoryLogic) ListCategory(in *pb.ListCategoryReq) (*pb.ListCategoryResp, error) {
	logx.Info("ListCategory req:", in)
	var list []dao.Users
	list, total, err := l.repo.List(l.ctx, 1, 10)
	if err != nil {
		logx.Errorf("ListCategory l.repo.List err:%s", err.Error())
		return nil, err
	}
	var respList []*pb.ListCategoryItem
	for _, item := range list {
		respList = append(respList, &pb.ListCategoryItem{
			Name: item.UserName,
		})
	}
	if respList != nil {
		rs, err := json.Marshal(respList)
		if err != nil {
			logx.Errorf("ListCategory json.Marshal err:%s", err.Error())
			return nil, err
		}
		_, err = l.svcCtx.RedisCluster.Set(l.ctx, "goods", string(rs), 0).Result()
		if err != nil {
			logx.Errorf("ListCategory redis set err:%s", err.Error())
			return nil, err
		}
	}
	return &pb.ListCategoryResp{
		ErrNo:  0,
		ErrMsg: "OK",
		Data: &pb.ListGategoryData{
			Page:  in.Page,
			Size:  in.Size,
			Total: total,
			Data:  respList,
		},
	}, nil
}
